<?php
/*********************************************************************\
*  Copyright (c) 1998-2013, TH. All Rights Reserved.
*  Author :lwj
*  FName  :ruku.php
*  Time   :2019.10.22
*  Remark :成品入库管理
\*********************************************************************/
FLEA::loadClass('TMIS_Controller');
class Controller_Sample_Report  extends TMIS_Controller {
    var $reportKucunListId = '1-3';
    function __construct() {
        $this->_modelExample = FLEA::getSingleton('Model_Sample_Kucun');
        // $this->_modelChuku2Product = FLEA::getSingleton('Model_Sample_Chuku2Product');
    }


    /**
     * 库存收发存报表
     * Time：2019/02/26 15:56:33
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionReportKucun(){
        $this->authCheck($this->reportKucunListId);
        $dateFrom = $_GET['dateFrom'] ? $_GET['dateFrom'] : date('Y-m-d',mktime(0,0,0,date('m')-3,date('d'),date('Y')));
        $dateTo = $_GET['dateTo'] ? $_GET['dateTo'] : date('Y-m-d');

        $searchItems = array(
            'dateRange' =>array($dateFrom , $dateTo),
            'barCode'   =>$_GET['barCode'].'',
            'proDesc'   =>$_GET['proDesc'].'',
            'type'      =>$_GET['type'] ? array($_GET['type']) : array(),
            'hzlId'     =>$_GET['hzlId'].'',
            'productId' =>$_GET['productId'].'',
            'kuweiId'   =>array(),
            'haveKc'    =>array(),
        );

        $smarty = & $this->_getView();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2TableNew();
        // foreach ($fileds as & $fv) {
        //     $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        // }
        $arrFieldInfo = array_merge(
            array(
                "code"      =>array('text'=>"产品编号",'width'=>'100'),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                // "proCode"   =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'120'),
            ),
            $fileds
            ,array(
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'100'),
                "gexing"    =>array('text'=>"格型",'width'=>'90','forKeySearch'=>true),
                "zuzhi"     =>array('text'=>"组织",'width'=>'90','forKeySearch'=>true),
                // "tanli"     =>array('text'=>"弹力",'width'=>'90','forKeySearch'=>true),
                "hzl"       =>array('text'=>"后整理工艺",'width'=>'100'),
                "type"       =>array('text'=>"样品类型",'width'=>'100'),
                "kuweiName"  =>array('text'=>"库位",'width'=>'100'),
                "cntInit"    =>array('text'=>"期初",'width'=>'100'),
                "cntRuku"    =>array('text'=>"本期入库",'width'=>'100','type'=>'component','options'=>array(
                    'type'      =>'iframe-dialog',
                    'action'    =>url('Sample_Ruku','ReportViewList'),
                    'params'    =>array('showFiled'=>'cntRuku'),
                    'getParams' =>array('productId','kuweiId','proDesc','type','dateFrom','dateTo','code'),
            )),
                "cntChuku"   =>array('text'=>"本期出库",'width'=>'100','type'=>'component','options'=>array(
                    'type'      =>'iframe-dialog',
                    'action'    =>url('Sample_Chuku','ReportViewList'),
                    'params'    =>array('showFiled'=>'cntChuku'),
                    'getParams' =>array('productId','kuweiId','proDesc','type','dateFrom','dateTo','code'),
            )),
                "cntKucun"   =>array('text'=>"库存",'width'=>'100'),
                'otherDesc'  => array('text'=>'其他描述','width'=>'150','type'=>'html')
            )
        );

        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('action', $this->_url('GetKucunRows'));
        $smarty->assign('searchItems', $searchItems);
        $smarty->assign('colsForKey', array(
          // array('text'=>'产品关键字','col'=>'key'),
          array('text' =>'产品编号','col'=>'code'),
          array('text' =>'产品名称','col'=>'proName'),
          // array('text' =>'规格','col'=>'guige'),
          // array('text'=>'条码','col'=>'barCode'),
          array('text' =>'格型','col'=>'gexing'),
          array('text' =>'组织','col'=>'zuzhi'),
          array('text' =>'花型颜色','col'=>'proDesc'),
        ));
        // $smarty->assign('addUrl',$this->_url('Add'));
        $smarty->assign('rowKey','rid');
        $smarty->display('TableList_v1.1.tpl');
    }

    /**
     * 库存列表
     * Time：2019/10/28 14:55:31
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    public function actionGetKucunRows(){
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }

        ini_set('memory_limit', '256M');

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;
        if($arr['dateRange']){
            list($dateFrom ,$dateTo) = $arr['dateRange'];
        }else{
          $dateFrom = '1900-01-01';
          $dateTo   = date('Y-m-d');
        }
        $strCon = "";
        if($arr['productId']){
          $strCon .= " and productId='{$arr['productId']}'";
        }
        if($arr['proDesc']){
          $strCon .= " and proDesc like '%{$arr['proDesc']}%'";
        }
        if($arr['code']){
          $strCon .= " and code like '%{$arr['code']}%'";
        }
        if($arr['gexing']!='') {
            $strCon.=" and gexing like '%{$arr['gexing']}%'";
        }
        if($arr['zuzhi']!='') {
            $strCon.=" and zuzhi like '%{$arr['zuzhi']}%'";
        }
        // if($arr['tanli']!='') {
        //     $strCon.=" and tanli like '%{$arr['tanli']}%'";
        // }
        if($arr['hzlId']!='') {
            $strCon.=" and find_in_set({$arr['hzlId']} ,`hzlId`)";
        }
        if($arr['type']) {
            foreach ($arr['type'] as & $a) {
                $a = "'{$a}'";
            }
            $type = join(',' ,$arr['type']);
            $strCon.=" and type in ({$type})";
        }
        if($arr['kuweiId']) {
            $type = join(',' ,$arr['kuweiId']);
            $strCon.=" and kuweiId in ({$kuweiId})";
        }

        // 查找产品信息
        $pWhere = "";
        if($arr['proCode']){
          $pWhere .= " and proCode like '%{$arr['proCode']}%'";
        }
        if($arr['proName']){
          $pWhere .= " and proName like '%{$arr['proName']}%'";
        }
        if($arr['guige']){
          $pWhere .= " and guige like '%{$arr['guige']}%'";
        }
        if($pWhere){
          $_pSql = "SELECT id from jichu_product where 1 {$pWhere}";
          $tmp = $this->_modelExample->findBySql($_pSql);
          $_proIds = join(',' , array_col_values($tmp ,'id'));
          if($_proIds) $strCon .= " and productId in({$_proIds})";
          else $strCon .= " and productId = '-1'";
        }

        // dump($_proIds);exit;
        $strGroup ="productId,type,kuweiId,proDesc,code,gexing,zuzhi,hzlId";
        $strFiled ="";
        $sqlUnion="select {$strGroup}{$strFiled},sum(cnt) as cntInit,0 as cntRuku,0 as cntChuku
        from `sample_kucun` where dateFasheng<'{$dateFrom}'
         {$strCon} group by {$strGroup}
        union
        select {$strGroup}{$strFiled},
        0 as cntInit,sum(cnt) as cntRuku,0 as cntChuku
        from `sample_kucun` where
        dateFasheng>='{$dateFrom}' and dateFasheng<='{$dateTo}'
        and rukuId>0  {$strCon} group by {$strGroup}
        union
        select {$strGroup}{$strFiled},
        0 as cntInit,0 as cntRuku,sum(cnt*-1) as cntChuku
        from `sample_kucun` where
        dateFasheng>='{$dateFrom}' and dateFasheng<='{$dateTo}'
        and chukuId>0  {$strCon} group by {$strGroup}";

        $sql="select
        {$strGroup}{$strFiled},sum(cntInit) as cntInit,sum(cntRuku) as cntRuku,sum(cntChuku) as cntChuku
        from ({$sqlUnion}) as x
        group by {$strGroup} ";
        //having判断显示库存情况
        if($arr['haveKc'] == 'kucun'){
          $having = " (sum(cntInit)+sum(cntRuku)-sum(cntChuku)) <> 0";
        }elseif($arr['haveKc'] == 'ruku'){
          $having = " sum(cntRuku) <> 0";
        }elseif($arr['haveKc'] == 'chuku'){
          $having = " sum(cntChuku) <> 0";
        }else{
          $having = " sum(cntInit)<>0 or sum(cntRuku)<>0 or sum(cntChuku)<>0";
        }
        $sql .= " having {$having} order by productId asc,code asc,kuweiId asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();
        // dump($rowset);exit;

        foreach ($rowset as $key => & $v) {
            $v['rid'] = $v['productId'].'-'.$v['code'].'-'.$v['kuweiId'].'-'.$key;
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);
            //库位
            $_tmp = $modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_tmp['kuweiName'];

          //其他数据

          $v['cntInit'] = round($v['cntInit'],6);
          $v['cntRuku'] = round($v['cntRuku'],6);
          $v['cntChuku'] = round($v['cntChuku'],6);


          $v['cntKucun'] = round($v['cntInit'] + $v['cntRuku'] - $v['cntChuku'], 2);

          !$v['cntInit'] && $v['cntInit']       = '';
          !$v['cntRuku'] && $v['cntRuku']       = '';
          !$v['cntChuku'] && $v['cntChuku']     = '';
          !$v['cntKucun'] && $v['cntKucun']     = '';


          // 查找后整理工艺
          if($v['hzlId']){
              $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
              $tmp = $this->_modelExample->findBySql($sql);
              $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
          }

          $v['key'] = $key+1;
          $v['dateFrom'] = $dateFrom;
          $v['dateTo'] = $dateTo;
        }

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;
    }

    /**
     * 给出库的时候选择库存的时候用的
     * Time：2019/10/28 15:24:42
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionPopupSelect(){
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }

        ini_set('memory_limit', '256M');

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        //选择的时候需要用到
        if($arr['proCode']){
          $wProduct = " and proCode like '%{$arr['proCode']}%'";
        }
        if($arr['proName']){
          $wProduct = " and proName like '%{$arr['proName']}%'";
        }
        if($wProduct){
          $sql2 = "SELECT id from jichu_product where 1 {$wProduct} limit 0,128";
          $tmp = $modelProduct->findBySql($sql2);
          if($tmp){
            $_proId = join(',' ,array_col_values($tmp ,'id'));
            !$_proId && $_proId = '-1';
          }else{
            $_proId = '-1';
          }

          $strCon .= " and productId in({$_proId})";
        }

        if($arr['barCode']){
          $strCon = " and code like '%{$arr['barCode']}%'";
        }

        if($arr['proDesc']){
          $strCon = " and proDesc like '%{$arr['proDesc']}%'";
        }

        // dump($strCon);exit;

        $strGroup ="productId,type,kuweiId,proDesc,code";
        $sql="select {$strGroup} ,sum(cnt) as cnt
        from {$this->_modelExample->tableName}
        where 1 {$strCon}
        group by {$strGroup} ";
        $sql .= " having sum(cnt) <> 0 order by productId asc,code asc,kuweiId asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();
        // dump($rowset);exit;

        foreach ($rowset as $key => & $v) {
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];

            $v['productDesc'] = $v['code'].' - '.$v['kindName'].' - '. $v['proName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);
            //库位
            $_tmp = $modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_tmp['kuweiName'];

          //其他数据

          $v['cnt'] = round($v['cnt'],6);
          $v['kucun'] = $v['cnt'];
        }

        //表头信息
        $modelKind = FLEA::getSingleton("Model_Jichu_ProKind");
        $fileds = $modelKind->fileds2Table();
        foreach ($fileds as & $fv) {
            $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 80 ? mb_strlen($fv,'utf8')*18 : 80));
        }
        $arr_field_info = array_merge(
            array(
                'code'      => array('text'=>'产品编号','width'=>'100'),
                'kindName'  => array('text'=>'产品类别','width'=>'90'),
                // 'proCode'   => array('text'=>'编号','width'=>'100'),
                'proName'   => array('text'=>'产品名称','width'=>'100'),
                'proDesc'   => array('text'=>'花型颜色','width'=>'100'),
                "type"      => array('text'=>"样品类型",'width'=>'100'),
                "kuweiName" => array('text'=>"库位",'width'=>'100'),
                'cnt'       => array('text'=>'库存','width'=>'100'),
            )
            ,$fileds
            ,array(
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
            )
        );

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>$arr_field_info,
          'rows'    =>$rowset,
        );

        echo json_encode($ret);exit;
    }
    /**
     * 库存收发存报表
     * Time：2019/02/26 15:56:33
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionReportProduct(){
        $this->authCheck('1-4');

        $searchItems = array(
            'dateRange' =>array(date('Y-m-d',mktime(0,0,0,date('m')-3,date('d'),date('Y'))),date('Y-m-d')),
            'code'   =>'',
            'proDesc'   =>'',
            'type'      =>array(),
            'productId' =>'',
            // 'kuweiId'   =>'',
        );

        $smarty = & $this->_getView();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2TableNew();
        // foreach ($fileds as & $fv) {
        //     $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        // }
        $arrFieldInfo = array_merge(
            array(
                "code"      =>array('text'=>"产品编号",'width'=>'100','forKeySearch'=>true),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                // "proCode"   =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'120'),
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'140','forKeySearch'=>true),
            )
            ,$fileds
            ,array(
                "type"       =>array('text'=>"样品类型",'width'=>'100'),
                "num"        =>array('text'=>"采样次数",'width'=>'100'),
                "cycnt"      =>array('text'=>"数量",'width'=>'100','type'=>'component','options'=>array(
                    'type'      =>'iframe-dialog',
                    'action'    =>url('Sample_Chuku','ReportViewList'),
                    'params'    =>array('showFiled'=>'cycnt'),
                    'getParams' =>array('productId','proDesc','type','dateFrom','dateTo','code'),
                )),
                'otherDesc'  => array('text'=>'其他描述','width'=>'','type'=>'html')
            )
        );

        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('action', $this->_url('GetRowsReportProduct'));
        $smarty->assign('searchItems', $searchItems);
        $smarty->assign('rowKey','rid');
        $smarty->display('TableList_v1.1.tpl');
    }


    /**
     * 采样样品汇总
     * Time：2019/03/26 16:23:57
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionGetRowsReportProduct(){
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }

        ini_set('memory_limit', '256M');

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        // dump($strCon);exit;
        $sql = "SELECT x.productId,x.proDesc,sum(x.cnt) as cycnt,x.type,count(x.chukuId) as num,x.code
                from sample_chuku2product x
                left join sample_chuku y on x.chukuId=y.id
                where 1";
        if($arr['productId']){
            $sql .= " and x.productId = '{$arr['productId']}'";
        }
        if($arr['proDesc']){
            $sql .= " and x.proDesc like '%{$arr['proDesc']}%'";
        }
        if($arr['code']){
            $sql .= " and x.code like '%{$arr['code']}%'";
        }
        if($arr['dateRange']){
            list($dateFrom ,$dateTo) = $arr['dateRange'];
        }else{
          $dateFrom = '1900-01-01';
          $dateTo   = date('Y-m-d');
        }
        $sql .= " and y.chukuDate >= '{$dateFrom}' and y.chukuDate <= '{$dateTo}'";
        if($arr['type']) {
            foreach ($arr['type'] as & $a) {
                $a = "'{$a}'";
            }
            $type = join(',' ,$arr['type']);
            $sql.=" and x.type in ({$type})";
        }
        $sql .= " group by x.productId,x.type,x.proDesc order by cycnt desc,num desc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();
        // dump($rowset);exit;

        foreach ($rowset as $key => & $v) {
          $v['rid'] = $v['productId'].'-'.$v['type'].'-'.$v['proDesc'];
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);


            //其他数据
            $v['cycnt'] = round($v['cycnt'],6);

            $v['key'] = $key+1;
            $v['dateFrom'] = $dateFrom;
            $v['dateTo'] = $dateTo;
        }

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;

    }

    /**
     * 采样人汇总
     * Time：2019/03/26 16:23:57
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionReportEmploy(){
        $this->authCheck('1-5');

        $searchItems = array(
            'dateRange' =>array(date('Y-m-d',mktime(0,0,0,date('m')-3,date('d'),date('Y'))),date('Y-m-d')),
            // 'proDesc'   =>'',
            // 'barCode'   =>'',
            // 'type'      =>array(),
            'productId' =>'',
            'employId'  =>array(),
        );

        $smarty = & $this->_getView();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2TableNew();
        // foreach ($fileds as & $fv) {
        //     $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        // }
        $arrFieldInfo = array_merge(
            array(
                "employName"=>array('text'=>"采样人",'width'=>'100'),
                // "code"      =>array('text'=>"条码",'width'=>'100','forKeySearch'=>true),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                "code"      =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'120'),
                // "proDesc"   =>array('text'=>"花型颜色",'width'=>'140','forKeySearch'=>true),
            )
            ,$fileds
            ,array(
                // "type"       =>array('text'=>"样品类型",'width'=>'100'),
                "num"        =>array('text'=>"采样次数",'width'=>'100'),
                "cycnt"      =>array('text'=>"数量",'width'=>'100','type'=>'component','options'=>array(
                    'type'      =>'iframe-dialog',
                    'action'    =>url('Sample_Chuku','ReportViewList'),
                    'params'    =>array('showFiled'=>'cycnt'),
                    'getParams' =>array('productId','dateFrom','dateTo','employId'),
                )),
                'otherDesc'  => array('text'=>'其他描述','width'=>'','type'=>'html')
            )
        );

        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('action', $this->_url('GetRowsReportEmploy'));
        $smarty->assign('searchItems', $searchItems);
        $smarty->assign('rowKey','rid');
        $smarty->display('TableList_v1.1.tpl');
    }


    /**
     * 采样样品汇总
     * Time：2019/03/26 16:23:57
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionGetRowsReportEmploy(){
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }

        ini_set('memory_limit', '256M');

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        // dump($strCon);exit;
        $sql = "SELECT x.productId,sum(x.cnt) as cycnt,x.type,x.proDesc,x.code,count(x.id) as num,e.employName,y.employId
                from sample_chuku2product x
                left join sample_chuku y on y.id=x.chukuId
                left join jichu_employ e on e.id=y.employId
                where 1";
        if($arr['productId']){
            $sql .= " and x.productId = '{$arr['productId']}'";
        }
        // if($arr['proDesc']){
        //     $sql .= " and x.proDesc like '%{$arr['proDesc']}%'";
        // }
        // if($arr['barCode']){
        //     $sql .= " and x.code like '%{$arr['barCode']}%'";
        // }
        if($arr['code']){
            $sql .= " and x.code like '%{$arr['code']}%'";
        }
        if($arr['dateRange']){
            list($dateFrom ,$dateTo) = $arr['dateRange'];
        }else{
          $dateFrom = '1900-01-01';
          $dateTo   = date('Y-m-d');
        }
        $sql .= " and y.chukuDate >= '{$dateFrom}' and y.chukuDate <= '{$dateTo}'";

        // if($arr['type']) {
        //     foreach ($arr['type'] as & $a) {
        //         $a = "'{$a}'";
        //     }
        //     $type = join(',' ,$arr['type']);
        //     $sql.=" and x.type in ({$type})";
        // }
        if($arr['employId']) {
            $employId = join(',' ,$arr['employId']);
            $sql.=" and y.employId in ({$employId})";
        }
        $sql .= " group by x.productId,y.employId order by cycnt desc,num desc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();
        // dump($rowset);exit;

        foreach ($rowset as $key => & $v) {
          $v['rid'] = $v['productId'].'-'.$v['employId'];
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);

            //其他数据
            $v['cycnt'] = round($v['cycnt'],6);

            $v['key'] = $key+1;
            $v['dateFrom'] = $dateFrom;
            $v['dateTo'] = $dateTo;
        }

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;

    }


    function actionReportClient(){
        $this->authCheck('1-6');

        $searchItems = array(
            'dateRange' =>array(date('Y-m-d',mktime(0,0,0,date('m')-3,date('d'),date('Y'))),date('Y-m-d')),
            'proDesc'   =>'',
            'barCode'   =>'',
            'type'      =>array(),
            'productId' =>'',
            'clientId'  =>array(),
            'compName'  =>array(),
        );

        $smarty = & $this->_getView();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2TableNew();
        // foreach ($fileds as & $fv) {
        //     $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        // }
        $arrFieldInfo = array_merge(
            array(
                "compName"  =>array('text'=>"客户",'width'=>'100','forKeySearch'=>true),
                "code"      =>array('text'=>"产品编号",'width'=>'100','forKeySearch'=>true),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                // "proCode"   =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'120'),
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'140','forKeySearch'=>true),
            )
            ,$fileds
            ,array(
                "type"       =>array('text'=>"样品类型",'width'=>'100'),
                "num"        =>array('text'=>"采样次数",'width'=>'100'),
                "cycnt"      =>array('text'=>"数量",'width'=>'100','type'=>'component','options'=>array(
                    'type'      =>'comp-iframe-dialog',
                    'action'    =>url('Sample_Chuku','ReportViewList'),
                    'params'    =>array('showFiled'=>'cycnt'),
                    'getParams' =>array('productId','proDesc','type','dateFrom','dateTo','clientId'),
                )),
                'otherDesc'  => array('text'=>'其他描述','width'=>'','type'=>'html')
            )
        );

        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('actionLoadData', $this->_url('GetRowsReportClient'));
        $smarty->assign('searchItems', $searchItems);
        $smarty->assign('rowKey','rid');
        $smarty->display('Async/TableList.tpl');
    }


    /**
     * 采样样品汇总
     * Time：2019/03/26 16:23:57
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionGetRowsReportClient(){
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }

        ini_set('memory_limit', '256M');

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        // dump($strCon);exit;
        $sql = "SELECT x.productId,sum(x.cnt) as cycnt,x.type,x.proDesc,x.code,count(x.id) as num,c.compName,y.clientId
                from sample_chuku2product x
                left join sample_chuku y on y.id=x.chukuId
                left join jichu_client c on c.id=y.clientId
                where y.clientId > 0";
        // 按照采样人限制查看对应的数据
        $mUser = FLEA::getSingleton('Model_Acm_User');
        $traderArr = $mUser->getTraderIdByUser($_SESSION['USERID']);
        if($traderArr['_ALL_'] == false){
            $traderIds = join(',',$traderArr['Traders']);
            !$traderIds && $traderIds = '-1';
            $sql .= " and y.employId in ({$traderIds})";
        }

        if($arr['productId']){
            $sql .= " and x.productId = '{$arr['productId']}'";
        }
        if($arr['proDesc']){
            $sql .= " and x.proDesc like '%{$arr['proDesc']}%'";
        }
        if($arr['barCode']){
            $sql .= " and x.code like '%{$arr['barCode']}%'";
        }
        if($arr['code']){
            $sql .= " and x.code like '%{$arr['code']}%'";
        }
        if($arr['compName']){
            $sql .= " and c.compName like '%{$arr['compName']}%'";
        }
        if($arr['dateRange']){
            list($dateFrom ,$dateTo) = $arr['dateRange'];
        }else{
          $dateFrom = '1900-01-01';
          $dateTo   = date('Y-m-d');
        }
        $sql .= " and y.chukuDate >= '{$dateFrom}' and y.chukuDate <= '{$dateTo}'";

        if($arr['type']) {
            foreach ($arr['type'] as & $a) {
                $a = "'{$a}'";
            }
            $type = join(',' ,$arr['type']);
            $sql.=" and x.type in ({$type})";
        }
        if($arr['clientId']) {
            $clientId = join(',' ,$arr['clientId']);
            $sql.=" and y.clientId in ({$clientId})";
        }
        $sql .= " group by x.productId,x.type,y.clientId,x.proDesc order by cycnt desc,num desc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();
        // dump($rowset);exit;

        foreach ($rowset as $key => & $v) {
          $v['rid'] = $v['productId'].'-'.$v['type'].'-'.$v['clientId'].'-'.$v['proDesc'];
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);

            //其他数据
            $v['cycnt'] = round($v['cycnt'],6);

            $v['key'] = $key+1;
            $v['dateFrom'] = $dateFrom;
            $v['dateTo'] = $dateTo;
        }

        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;

    }


    /**
     * 用图片搜索样品
     * Time：2019/12/02 11:17:25
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionSearchByImage(){
        $this->authCheck('1-7');

        $searchItems = array(
            'ImageFile' =>'',
            // 'proDesc'   =>'',
            // 'productId' =>'',
            // 'type'      =>array(),
        );

        $smarty = & $this->_getView();

        $editButtons = array(
            array('text'=>'详细','type'=>'redirect','icon'=>'el-icon-detail','options'=>array(
                'url' =>$this->_url('Edit').'&id={productId}&ruku2proId={ruku2proId}',
            )),
        );

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2Table();
        foreach ($fileds as & $fv) {
            $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        }
        $arrFieldInfo = array_merge(
            array(
                "score"     =>array('text'=>"相似度",'width'=>'100'),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                "proCode"   =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'120'),
                "code"      =>array('text'=>"条码",'width'=>'100'),
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'140'),
                "type"      =>array('text'=>"样品类型",'width'=>'100'),
                // "kucun"     =>array('text'=>"库存数量",'width'=>'70'),
                "kucun"   =>array('text'=>"库存",'width'=>'100','type'=>'component','options'=>array(
                    'type'      =>'iframe-dialog',
                    'action'    =>url('Sample_Report','ReportKucun'),
                    'params'    =>array('showFiled'=>'kucun'),
                    'getParams' =>array('productId','proDesc','type','dateFrom','dateTo','barCode'),
                )),
                // "kuweiName" =>array('text'=>"库位",'width'=>'100'),
                'preview'   =>array('text'=>"预览",'width'=>'70','type'=>'component','options'=>array(
                    'type'=>'tip-preview-image',
                )),
            )
            ,$fileds
            ,array(
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
            )
        );

        $smarty->assign('title', '以图找样');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('action', $this->_url('GetRowsSearchImage'));
        $smarty->assign('searchItems', $searchItems);

        // $smarty->assign('addUrl',$this->_url('Add'));
        // $smarty->assign('menuRightTop', array(
        //     array('text'=>'新增(不关联制作单)','url'=>$this->_url('Add')),
        // ));
        $smarty->assign('sonTpl',array(
            'Jichu/TableProductList.js'
        ));

        $smarty->display('TableList_v1.1.tpl');
    }

    /**
     * 获取计划任务的数据
     * @author li
    */
    public function actionGetRowsSearchImage() {
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }
        FLEA::loadClass('TMIS_Common');

        $post = $this->axiosPost();

        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;

        //开始处理图【】
        //开始请求知图网接口，得到列表；仅显示前50个，并做分析处理，如果相似度没有超多80%,舍弃结果
        $apiResponse = array();
        if($arr['ImageFile'][0]['url'] != '' && file_exists($arr['ImageFile'][0]['url'])){
            $apiService = FLEA::getSingleton('Api_Lib_Req_Zhitu_ImageSim');
            $response = $apiService->searchImage(array(
                'path'       =>$arr['ImageFile'][0]['url'],
                'numperpage' =>'20',
            ));
            $apiResponse = json_decode($response ,true);
            @unlink(iconv('UTF-8','gb2312',$arr['ImageFile'][0]['url']));
        }


        //处理相似的数据
        $list = array();
        foreach ($apiResponse['resultList'] as $key => & $v) {
            list($code ,$imageId) = explode('_' ,$v['imgName']);
            //返回第一个数据或者相似度大于80%的数据
            if($v['score'] > 0.8 || count($list) < 1){
                $list[] = array('imageId'=>$imageId ,'score'=>$v['score']);
            }
        }

        //查找图片所在位置和分析数据
        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelImage = FLEA::getSingleton('Model_Jichu_Image');
        $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');
        $baseUrlstr = detect_uri_base();
        $serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));

        $rows = array();
        foreach ($list as & $l) {
            //先查询基础档案
            $sql = "SELECT id from jichu_product where find_in_set({$l['imageId']} , pic) and isSim='1'";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($tmp as & $v) {
                $rows[] = array(
                    'imageId'    =>$l['imageId'],
                    'score'      =>$l['score'],
                    'productId'  =>$v['id'],
                    'ruku2proId' =>0,
                );
            }

            //查找样品中的图片信息
            $sql = "SELECT x.id,x.rukuId,x.productId from sample_ruku2product x
            left join jichu_product y on x.productId=y.id
            where y.isSim='1' and find_in_set({$l['imageId']} , x.imageId) ";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($tmp as & $v) {
                $rows[] = array(
                    'imageId'    =>$l['imageId'],
                    'score'      =>$l['score'],
                    'productId'  =>$v['productId'],
                    'ruku2proId' =>$v['id'],
                    'rukuId'     =>$v['rukuId'],
                );
            }
        }

        //查找这些数据的详细信息
        foreach ($rows as & $v) {
            $v['score'] = round($v['score'] ,5);
            $v['score'] = ($v['score']*100).'%';
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);


            //如果有入库信息，再获取其中的详细数据
            $sql = "SELECT * from sample_ruku2product where id='{$v['ruku2proId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $tmp = $tmp[0];
            $v['type']      = strval($tmp['type']);
            $v['proDesc']   = strval($tmp['proDesc']);
            $v['memoView']  = strval($tmp['memoView']);
            $v['code']      = strval($tmp['code']);

            $v['barCode'] = $v['code'];
            $v['dateFrom']= '2000-01-01';
            $v['dateTo']= date('Y-m-d',mktime(0,0,0,date('m'),date('d'),date('Y')+2));

            //查找库存
            $kWhere = array();
            $kWhere['productId'] = $v['productId'];
            if($v['ruku2proId']){
                $kWhere['type'] = $v['type'];
                $kWhere['proDesc'] = $v['proDesc'];
                $kWhere['code'] = $v['code'];
            }
            $v['kucun'] = $modelKucun->getKucun($kWhere);
            $v['kucun'] = $v['kucun'] + 0;
            if($v['imageId']){
                $_tmp = $modelImage->find($v['imageId']);
                $v['imageSrc'][] = array(
                        'path'=>$_tmp['smallPath']
                    );
            }
        }

        $ret = array(
          'total'   =>count($rows),
          'columns' =>array(),
          'rows'    =>$rows,
        );
        echo json_encode($ret);exit;
    }

    /**
     * 拍照上传搜索的功能
     * Time：2019/12/02 13:06:10
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionUploadImageTmp(){
        $post = $this->axiosPost();
        // dump($post);
        if($post['type'] != 'base64'){
            $result = $this->_uploadImageTmp('',12,'',90);
        }else{
            $result = $this->_uploadImageBase64Tmp($post['image']);

            $pathinfo = pathinfo($result['imgPath']);
            $extType = $pathinfo['extension'];
            $extType = strtolower($extType);
            $size = getimagesize($result['imgPath']);
            $width  = $size[0];
            $height = $size[1];

            $pathRoot = 'upload/Images/';
            $rand = rand(10000, 99999);
            $randName = date('ymdHis') . $rand.'.'.$extType;
            $imagePath = $pathRoot.$randName;

            FLEA::loadClass('FLEA_Helper_Image');
            $img = & FLEA_Helper_Image::createFromFile($result['imgPath'], $extType);
            //计算压缩比例
            $max = 800;
            if($width > $height && $width > $max){
                $rate = $max / $width;
                $height2 = $height * $rate;
                $width2  = $max;
            }elseif($height > $width && $height > $max){
                $rate = $max / $height;
                $height2 = $max;
                $width2  = $width * $rate;
            }else{
                $height2 = $height;
                $width2  = $width;
            }

            $img->resampled($width2 , $height2);
            $img->saveAsJpeg($imagePath , 90);

            @unlink(iconv('UTF-8','gb2312',$result['imgPath']));
            $result['imgPath'] = $imagePath;
        }

        echo json_encode($result);
    }
}

?>